package com.cfc.stage1;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 罗马数字转整数，找规律呢是吧。哈哈哈
 *   https://leetcode.cn/problems/roman-to-integer/description/
 * @author: yangxuan10
 * @create: 2024-04-08 10:18
 **/
public class RomanToInt {

    @Test
    public void test(){

        System.out.println(romanToInt("LVIII"));
        System.out.println(romanToInt1("LVIII"));
    }

    public int romanToInt1(String s) {
        int sum = 0;
        char[] chars = s.toCharArray();
        int length = chars.length;
        for (int i = 0; i <length; i++) {
            //这里不用map用getValue，因为map里面的运算还是很多了呀...
            int value = getValue(chars[i]);
            if (i < length -1 && value < getValue(chars[i+1])) {
                sum -= value;
            } else {
                sum += value;
            }
        }
        return sum;
    }

    private int getValue(char ch) {
        switch(ch) {
            case 'I': return 1;
            case 'V': return 5;
            case 'X': return 10;
            case 'L': return 50;
            case 'C': return 100;
            case 'D': return 500;
            case 'M': return 1000;
            default: return 0;
        }
    }

    public int romanToInt(String s) {

        int sum = 0;
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i == chars.length -1) {
                Integer mapValue = map.get(chars[i]);
                if (mapValue !=null ) {
                    sum += mapValue;
                }
                break;
            }
            String map1Key = String.valueOf(chars[i]) + chars[i + 1];
            Integer map1Value = map1.get(map1Key);
            if (map1Value != null) {
                sum += map1Value;
                i++;
            } else {
                Integer mapValue = map.get(chars[i]);
                if (mapValue !=null ) {
                    sum += mapValue;
                }
            }
        }
        return sum;
    }

    Map<Character,Integer> map = new HashMap<Character,Integer>(){{
        put('I',1);
        put('V',5);
        put('X',10);
        put('L',50);
        put('C',100);
        put('D',500);
        put('M',1000);
    }};

    Map<String,Integer> map1 = new HashMap<String,Integer>(){{
        put("IV",4);
        put("IX",9);
        put("XL",40);
        put("XC",90);
        put("CD",400);
        put("CM",900);
    }};
}